<template>
  <div class="app-container">
    <!-- 查询条件区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="月份" prop="month">
        <el-date-picker
          v-model="queryParams.month"
          type="month"
          value-format="YYYY-MM"
          placeholder="请选择月份"
          style="width: 240px"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="部门" prop="departmentName">
        <el-select
          v-model="queryParams.departmentName"
          placeholder="请选择部门"
          clearable
          style="width: 240px"
        >
          <el-option v-for="dept in departments" :key="dept.value" :label="dept.label" :value="dept.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="提案人" prop="proposerName">
        <el-input
          v-model="queryParams.proposerName"
          placeholder="请输入提案人姓名"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评分状态" prop="scoreStatus">
        <el-select v-model="queryParams.scoreStatus" placeholder="请选择评分状态" clearable style="width: 240px">
          <el-option label="全部" value="all"></el-option>
          <el-option label="主管审核" value="supervisorScored"></el-option>
          <el-option label="经理审核" value="managerScored"></el-option>
          <el-option label="委员会审核" value="committeeScored"></el-option>
          <el-option label="已完成评分" value="scored"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    
    <!-- 提案数据表格 -->
    <el-table v-loading="loading" :data="proposalList">
      <el-table-column label="状态" align="center" prop="status" width="110" />
      <el-table-column label="月份" align="center" prop="month" width="100" />
      <el-table-column label="部门" align="center" prop="departmentName" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="提案人" align="center" prop="proposerName" width="100" />
      <el-table-column label="提案时间" align="center" prop="proposalTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.proposalTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提案名称" align="center" prop="title" width="150" :show-overflow-tooltip="true" />
      
      <el-table-column label="主管评分" align="center" width="100">
        <template #default="scope">
          <span :style="{ color: scope.row.supervisorTotalScore >= 30 ? '#F56C6C' : '#FF5733' }">
            {{ scope.row.supervisorTotalScore !== null ? scope.row.supervisorTotalScore : '-' }}
          </span>
        </template>
      </el-table-column>
      
      <el-table-column label="经理评分" align="center" width="100">
        <template #default="scope">
          <span :style="{ color: scope.row.managerTotalScore >= 30 ? '#F56C6C' : '#FF5733'}">
            {{ scope.row.managerTotalScore !== null ? scope.row.managerTotalScore : '-' }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="委员会评分" align="center" width="120">
        <template #default="scope">
          <span :style="{ color: scope.row.committeeTotalScore >= 30 ? '#F56C6C' : '#FF5733' }">
            {{ scope.row.committeeTotalScore !== null ? scope.row.committeeTotalScore : '-' }}
          </span>
        </template>
      </el-table-column>
      
      <el-table-column label="奖金" align="center" prop="bonus" width="100" />
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleScore(scope.row)">评分</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 评分对话框 -->
    <el-dialog :title="scoreTitle" v-model="scoreOpen" width="800px" append-to-body>
      <el-form ref="scoreRef" :model="scoreForm" :rules="scoreRules" label-width="120px">
        <!-- 基本信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="提案名称：" prop="title">
              <span>{{ scoreForm.title }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提案人：" prop="proposerName">
              <span>{{ scoreForm.proposerName }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门：" prop="departmentName">
              <span>{{ scoreForm.departmentName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月份：" prop="month">
              <span>{{ scoreForm.month }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 提案图片 -->
        <el-form-item label="提案图片：" v-if="scoreForm.image">
          <div v-if="scoreForm.image && scoreForm.image.includes(',')">
            <div v-for="(img, index) in scoreForm.image.split(',')" :key="index" style="margin-bottom: 10px;">
              <el-link 
                :href="getImageUrl(img)" 
                target="_blank" 
                type="primary"
                :underline="false">
                图片 {{ index + 1 }}
              </el-link>
            </div>
          </div>
          <div v-else-if="scoreForm.image">
            <el-link 
              :href="getImageUrl(scoreForm.image)" 
              target="_blank" 
              type="primary"
              :underline="false">
              查看图片
            </el-link>
          </div>
        </el-form-item>

        <!-- 提案内容 -->
        <el-form-item label="提案内容：" prop="content" :show-overflow-tooltip="true">
          <div class="proposal-content">{{ scoreForm.content }}</div>
        </el-form-item>

        <!-- 节省金额 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="持续节省：" prop="monthlySaving">
              <span>{{ scoreForm.monthlySaving || '0' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="一次性节省：" prop="oneTimeSaving">
              <span>{{ scoreForm.oneTimeSaving || '0' }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 评分标签页 -->
        <el-tabs type="card">
          <!-- 主管评分 -->
          <el-tab-pane label="主管评分">
            <el-form-item label="提案内容评价" prop="supervisorContentEvaluation">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="完整性" prop="supervisorCompleteness">
                    <el-input v-model.number="scoreForm.supervisorCompleteness" :min="0" @input="supervisorTotalScore"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="适用性" prop="supervisorApplicability">
                    <el-input v-model.number="scoreForm.supervisorApplicability" @input="supervisorTotalScore"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="创新性" prop="supervisorInnovation">
                    <el-input v-model.number="scoreForm.supervisorInnovation" :min="0" @input="supervisorTotalScore"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item label="项目实施评价" prop="supervisorImplementationEvaluation">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="安全环境" prop="supervisorSafetyEnvironment">
                    <el-input v-model.number="scoreForm.supervisorSafetyEnvironment" :min="0" @input="supervisorTotalScore"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="质量" prop="supervisorQuality">
                    <el-input v-model.number="scoreForm.supervisorQuality" :min="0" @input="supervisorTotalScore"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="效率" prop="supervisorEfficiency">
                    <el-input v-model.number="scoreForm.supervisorEfficiency" :min="0" @input="supervisorTotalScore"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="成本" prop="supervisorCost">
                    <el-input v-model.number="scoreForm.supervisorCost" :min="0" @input="supervisorTotalScore"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="推广度" prop="supervisorPromotion">
                    <el-input v-model.number="scoreForm.supervisorPromotion" :min="0" @input="supervisorTotalScore"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="努力度" prop="supervisorEffort">
                    <el-input v-model.number="scoreForm.supervisorEffort" :min="0" @input="supervisorTotalScore"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item label="主管总分" prop="supervisorTotalScore">
              <el-input v-model.number="scoreForm.supervisorTotalScore" disabled></el-input>
            </el-form-item>
          </el-tab-pane>

            <!-- 经理评分标签 -->
            <el-tab-pane label="经理评分">
              <el-form-item label="提案内容评价" prop="managerContentEvaluation">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="完整性" prop="managerCompleteness">
                      <el-input v-model.number="scoreForm.managerCompleteness" :min="0" @input="managerTotalScore"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="适用性" prop="managerApplicability">
                      <el-input v-model.number="scoreForm.managerApplicability" @input="managerTotalScore"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="创新性" prop="managerInnovation">
                      <el-input v-model.number="scoreForm.managerInnovation" :min="0" @input="managerTotalScore"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="项目实施评价" prop="managerImplementationEvaluation">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="安全环境" prop="managerSafetyEnvironment">
                      <el-input v-model.number="scoreForm.managerSafetyEnvironment" :min="0" @input="managerTotalScore"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="质量" prop="managerQuality">
                      <el-input v-model.number="scoreForm.managerQuality" :min="0" @input="managerTotalScore"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="效率" prop="managerEfficiency">
                      <el-input v-model.number="scoreForm.managerEfficiency" :min="0" @input="managerTotalScore"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="成本" prop="managerCost">
                      <el-input v-model.number="scoreForm.managerCost" :min="0" @input="managerTotalScore"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="推广度" prop="managerPromotion">
                      <el-input v-model.number="scoreForm.managerPromotion" :min="0" @input="managerTotalScore"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="努力度" prop="managerEffort">
                      <el-input v-model.number="scoreForm.managerEffort" :min="0" @input="managerTotalScore"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form-item>

              <!-- 经理总分 -->
              <el-form-item label="经理总分" prop="managerTotalScore">
                <el-input v-model.number="scoreForm.managerTotalScore" disabled></el-input>
              </el-form-item>
            </el-tab-pane>

            <!-- 委员会评分标签 -->
            <el-tab-pane label="委员会评分">
              <el-form-item label="提案内容评价" prop="committeeContentEvaluation">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="完整性" prop="committeeCompleteness">
                      <el-input v-model="scoreForm.committeeCompleteness" :min="0" @input="handleScoreInput('committeeCompleteness', $event); committeeTotalScore()"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="适用性" prop="committeeApplicability">
                      <el-input v-model="scoreForm.committeeApplicability" @input="handleScoreInput('committeeApplicability', $event); committeeTotalScore()"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="创新性" prop="committeeInnovation">
                      <el-input v-model="scoreForm.committeeInnovation" :min="0" @input="handleScoreInput('committeeInnovation', $event); committeeTotalScore()"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="项目实施评价" prop="committeeImplementationEvaluation">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="安全环境" prop="committeeSafetyEnvironment">
                      <el-input v-model="scoreForm.committeeSafetyEnvironment" :min="0" @input="handleScoreInput('committeeSafetyEnvironment', $event); committeeTotalScore()"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="质量" prop="committeeQuality">
                      <el-input v-model="scoreForm.committeeQuality" :min="0" @input="handleScoreInput('committeeQuality', $event); committeeTotalScore()"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="效率" prop="committeeEfficiency">
                      <el-input v-model="scoreForm.committeeEfficiency" :min="0" @input="handleScoreInput('committeeEfficiency', $event); committeeTotalScore()"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="成本" prop="committeeCost">
                      <el-input v-model="scoreForm.committeeCost" :min="0" @input="handleScoreInput('committeeCost', $event); committeeTotalScore()"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="推广度" prop="committeePromotion">
                      <el-input v-model="scoreForm.committeePromotion" :min="0" @input="handleScoreInput('committeePromotion', $event); committeeTotalScore()"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="努力度" prop="committeeEffort">
                      <el-input v-model="scoreForm.committeeEffort" :min="0" @input="handleScoreInput('committeeEffort', $event); committeeTotalScore()"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form-item>

              <!-- 委员会总分 -->
              <el-form-item label="委员会总分" prop="committeeTotalScore">
                <el-input v-model.number="scoreForm.committeeTotalScore" disabled></el-input>
              </el-form-item>
            </el-tab-pane>

            <!-- 可行性评估标签 -->
            <el-tab-pane label="可行性评估">
              <el-form-item label="评估部门" prop="feasibilityDepartment">
                <el-select v-model="scoreForm.feasibilityDepartment" placeholder="请选择评估部门" style="width: 100%">
                  <el-option v-for="dept in departments" :key="dept.value" :label="dept.label" :value="dept.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="评估结果" prop="feasibilityResult">
                <el-radio-group v-model="scoreForm.feasibilityResult" @change="handleFeasibilityResultChange">
                  <el-radio label="采纳">采纳</el-radio>
                  <el-radio label="不采纳">不采纳</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="评估时间" prop="feasibilityTime">
                <el-date-picker 
                  v-model="scoreForm.feasibilityTime" 
                  type="date" 
                  style="width: 100%;"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择评估时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="评估意见" prop="feasibilityOpinion">
                <el-input 
                  v-model="scoreForm.feasibilityOpinion" 
                  type="textarea" 
                  :rows="3"
                  placeholder="请输入评估意见">
                </el-input>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="scoreOpen = false">取 消</el-button>
          <el-button type="primary" @click="submitScoreForm('modify')">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProposalAudit">

// 引入依赖
import { listScoreProposals, submitScore, getProposal } from "@/api/ciinput/proposal";
import { departments , getImageUrl, calculateBonus } from "@/utils/proposalData";

const { proxy } = getCurrentInstance();
const baseUrl = import.meta.env.VITE_APP_BASE_API;

// 响应式数据
const proposalList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const scoreOpen = ref(false);
const scoreTitle = ref("");
const hasImplementers = computed(() => {
  const form = detailForm.value;
  return form.implementer1Name || form.implementer1EmployeeId ||
         form.implementer2Name || form.implementer2EmployeeId ||
         form.implementer3Name || form.implementer3EmployeeId ||
         form.implementer4Name || form.implementer4EmployeeId ||
         form.implementer5Name || form.implementer5EmployeeId;
});

// 旧值
const originalScoreData = ref({});

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  month: undefined,
  departmentName: undefined,
  proposerName: undefined,
  scoreStatus: "supervisorScored"
});

// 详情表单数据
const detailForm = ref({});

// 评分表单数据
const scoreForm = ref({
  id: null,
  title: '',
  content: '',
  proposerName: '',
  status: '',
  month: '',
  departmentName: '',
  proposalTime: null,
  proposalTypeName: '',
  categoryName: '',
  isCompanyPromoted: false,
  isFinancePromoted: false,
  isQualityPromoted: false,
  bonus: 0,
  monthlySaving: 0,
  oneTimeSaving: 0,
  feasibilityDepartment: '',
  feasibilityResult: '采纳',
  feasibilityTime: null,
  feasibilityOpinion: '采纳',
  image: null,

  supervisorCompleteness: null,
  supervisorApplicability: null,
  supervisorInnovation: null,
  supervisorSafetyEnvironment: null,
  supervisorQuality: null,
  supervisorEfficiency: null,
  supervisorCost: null,
  supervisorPromotion: null,
  supervisorEffort: null,

  managerCompleteness: null,
  managerApplicability: null,
  managerInnovation: null,
  managerSafetyEnvironment: null,
  managerQuality: null,
  managerEfficiency: null,
  managerCost: null,
  managerPromotion: null,
  managerEffort: null,

  committeeCompleteness: null,
  committeeApplicability: null,
  committeeInnovation: null,
  committeeSafetyEnvironment: null,
  committeeQuality: null,
  committeeEfficiency: null,
  committeeCost: null,
  committeePromotion: null,
  committeeEffort: null,

  supervisorTotalScore: null,
  managerTotalScore: null,
  committeeTotalScore: null
});

// 数字验证
const NumberValidator = (message) => {
  return [
    { 
      validator: (rule, value, callback) => {
        if (value !== null && value !== undefined && value !== '') {
          if (isNaN(Number(value))) {
            callback(new Error(message));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ];
};

// 定义评分表单验证规则
const scoreRules = ref({
  supervisorCompleteness: NumberValidator("请输入完整性评分"),
  supervisorApplicability: NumberValidator("请输入适用性评分"),
  supervisorInnovation: NumberValidator("请输入创新性评分"),
  supervisorSafetyEnvironment: NumberValidator("请输入安全环境评分"),
  supervisorQuality: NumberValidator("请输入质量评分"),
  supervisorEfficiency: NumberValidator("请输入效率评分"),
  supervisorCost: NumberValidator("请输入成本评分"),
  supervisorPromotion: NumberValidator("请输入推广度评分"),
  supervisorEffort: NumberValidator("请输入努力度评分"),
  
  managerCompleteness: NumberValidator("请输入完整性评分"),
  managerApplicability: NumberValidator("请输入适用性评分"),
  managerInnovation: NumberValidator("请输入创新性评分"),
  managerSafetyEnvironment: NumberValidator("请输入安全环境评分"),
  managerQuality: NumberValidator("请输入质量评分"),
  managerEfficiency: NumberValidator("请输入效率评分"),
  managerCost: NumberValidator("请输入成本评分"),
  managerPromotion: NumberValidator("请输入推广度评分"),
  managerEffort: NumberValidator("请输入努力度评分"),

  committeeCompleteness: NumberValidator("请输入完整性评分"),
  committeeApplicability: NumberValidator("请输入适用性评分"),
  committeeInnovation: NumberValidator("请输入创新性评分"),
  committeeSafetyEnvironment: NumberValidator("请输入安全环境评分"),
  committeeQuality: NumberValidator("请输入质量评分"),
  committeeEfficiency: NumberValidator("请输入效率评分"),
  committeeCost: NumberValidator("请输入成本评分"),
  committeePromotion: NumberValidator("请输入推广度评分"),
  committeeEffort: NumberValidator("请输入努力度评分"),
  
  feasibilityDepartment: [
    { message: "请选择评估部门", trigger: "change" }
  ],
  feasibilityResult: [
    { message: "请选择评估结果", trigger: "change" }
  ],
  feasibilityTime: [
    { message: "请选择评估时间", trigger: "change" }
  ],
  feasibilityOpinion: [
    { message: "请输入评估意见", trigger: "blur" }
  ]
});

/** 查询提案列表 */
function getList() {
  loading.value = true;
  listScoreProposals(queryParams.value).then(response => {
    proposalList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    // 出错时重置列表和总数
    proposalList.value = [];
    total.value = 0;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.scoreStatus = undefined;
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  handleQuery();
}

/** 评分提案 */
function handleScore(row) {
  // 先获取完整的提案数据
  getProposal(row.id).then(response => {
    const proposalData = response.data;
    const today = new Date().toISOString().slice(0, 10); 
    
    //console.log("从数据库获取的提案数据:", proposalData);
    
    // 构建评分表单数据，确保所有字段都被正确处理
    const scoreData = {
      id: proposalData.id,
      title: proposalData.title || '',
      content: proposalData.content || '',
      proposerName: proposalData.proposerName || '',
      status: proposalData.status || '',
      month: proposalData.month || '',
      departmentName: proposalData.departmentName || '',
      proposalTime: proposalData.proposalTime || null,
      proposalTypeName: proposalData.proposalTypeName || '',
      categoryName: proposalData.categoryName || '',
      isCompanyPromoted: proposalData.isCompanyPromoted || false,
      isFinancePromoted: proposalData.isFinancePromoted || false,
      isQualityPromoted: proposalData.isQualityPromoted || false,
      image: proposalData.image || null,
      
      bonus: proposalData.bonus !== undefined && proposalData.bonus !== null ? Number(proposalData.bonus) : 0,
      monthlySaving: proposalData.monthlySaving !== undefined && proposalData.monthlySaving !== null ? Number(proposalData.monthlySaving) : 0,
      oneTimeSaving: proposalData.oneTimeSaving !== undefined && proposalData.oneTimeSaving !== null ? Number(proposalData.oneTimeSaving) : 0,
      feasibilityDepartment: proposalData.feasibilityDepartment || '',
      feasibilityResult: proposalData.feasibilityResult || '采纳',
      feasibilityTime: proposalData.feasibilityTime || today,
      feasibilityOpinion: proposalData.feasibilityOpinion || '采纳',

      // 主管评分项
      supervisorCompleteness: proposalData.supervisorCompleteness !== undefined && proposalData.supervisorCompleteness !== null ? Number(proposalData.supervisorCompleteness) : null,
      supervisorApplicability: proposalData.supervisorApplicability !== undefined && proposalData.supervisorApplicability !== null ? Number(proposalData.supervisorApplicability) : null,
      supervisorInnovation: proposalData.supervisorInnovation !== undefined && proposalData.supervisorInnovation !== null ? Number(proposalData.supervisorInnovation) : null,
      supervisorSafetyEnvironment: proposalData.supervisorSafetyEnvironment !== undefined && proposalData.supervisorSafetyEnvironment !== null ? Number(proposalData.supervisorSafetyEnvironment) : null,
      supervisorQuality: proposalData.supervisorQuality !== undefined && proposalData.supervisorQuality !== null ? Number(proposalData.supervisorQuality) : null,
      supervisorEfficiency: proposalData.supervisorEfficiency !== undefined && proposalData.supervisorEfficiency !== null ? Number(proposalData.supervisorEfficiency) : null,
      supervisorCost: proposalData.supervisorCost !== undefined && proposalData.supervisorCost !== null ? Number(proposalData.supervisorCost) : null,
      supervisorPromotion: proposalData.supervisorPromotion !== undefined && proposalData.supervisorPromotion !== null ? Number(proposalData.supervisorPromotion) : null,
      supervisorEffort: proposalData.supervisorEffort !== undefined && proposalData.supervisorEffort !== null ? Number(proposalData.supervisorEffort) : null,

      // 经理评分项
      managerCompleteness: proposalData.managerCompleteness !== undefined && proposalData.managerCompleteness !== null ? Number(proposalData.managerCompleteness) : null,
      managerApplicability: proposalData.managerApplicability !== undefined && proposalData.managerApplicability !== null ? Number(proposalData.managerApplicability) : null,
      managerInnovation: proposalData.managerInnovation !== undefined && proposalData.managerInnovation !== null ? Number(proposalData.managerInnovation) : null,
      managerSafetyEnvironment: proposalData.managerSafetyEnvironment !== undefined && proposalData.managerSafetyEnvironment !== null ? Number(proposalData.managerSafetyEnvironment) : null,
      managerQuality: proposalData.managerQuality !== undefined && proposalData.managerQuality !== null ? Number(proposalData.managerQuality) : null,
      managerEfficiency: proposalData.managerEfficiency !== undefined && proposalData.managerEfficiency !== null ? Number(proposalData.managerEfficiency) : null,
      managerCost: proposalData.managerCost !== undefined && proposalData.managerCost !== null ? Number(proposalData.managerCost) : null,
      managerPromotion: proposalData.managerPromotion !== undefined && proposalData.managerPromotion !== null ? Number(proposalData.managerPromotion) : null,
      managerEffort: proposalData.managerEffort !== undefined && proposalData.managerEffort !== null ? Number(proposalData.managerEffort) : null,

      // 委员会评分项
      committeeCompleteness: proposalData.committeeCompleteness !== undefined && proposalData.committeeCompleteness !== null ? Number(proposalData.committeeCompleteness) : null,
      committeeApplicability: proposalData.committeeApplicability !== undefined && proposalData.committeeApplicability !== null ? Number(proposalData.committeeApplicability) : null,
      committeeInnovation: proposalData.committeeInnovation !== undefined && proposalData.committeeInnovation !== null ? Number(proposalData.committeeInnovation) : null,
      committeeSafetyEnvironment: proposalData.committeeSafetyEnvironment !== undefined && proposalData.committeeSafetyEnvironment !== null ? Number(proposalData.committeeSafetyEnvironment) : null,
      committeeQuality: proposalData.committeeQuality !== undefined && proposalData.committeeQuality !== null ? Number(proposalData.committeeQuality) : null,
      committeeEfficiency: proposalData.committeeEfficiency !== undefined && proposalData.committeeEfficiency !== null ? Number(proposalData.committeeEfficiency) : null,
      committeeCost: proposalData.committeeCost !== undefined && proposalData.committeeCost !== null ? Number(proposalData.committeeCost) : null,
      committeePromotion: proposalData.committeePromotion !== undefined && proposalData.committeePromotion !== null ? Number(proposalData.committeePromotion) : null,
      committeeEffort: proposalData.committeeEffort !== undefined && proposalData.committeeEffort !== null ? Number(proposalData.committeeEffort) : null,

      // 总分
      supervisorTotalScore: proposalData.supervisorTotalScore !== undefined && proposalData.supervisorTotalScore !== null ? Number(proposalData.supervisorTotalScore) : null,
      managerTotalScore: proposalData.managerTotalScore !== undefined && proposalData.managerTotalScore !== null ? Number(proposalData.managerTotalScore) : null,
      committeeTotalScore: proposalData.committeeTotalScore !== undefined && proposalData.committeeTotalScore !== null ? Number(proposalData.committeeTotalScore) : null
    };

    //console.log("构建的评分表单数据:", scoreData);
    
    // 填充表单数据
    scoreForm.value = scoreData;
    
    // 保存原始数据用于比较
    originalScoreData.value = { ...scoreData };
    
    // 计算总分
    supervisorTotalScore();
    managerTotalScore();
    committeeTotalScore();

    scoreTitle.value = "提案评分";
    scoreOpen.value = true;
    
    // 在下一个tick中再次计算总分，确保数据已经正确绑定到表单中
    nextTick(() => {
      supervisorTotalScore();
      managerTotalScore();
      committeeTotalScore();
      //console.log("表单数据更新后:", scoreForm.value);
    });
  }).catch(error => {
    console.error("获取提案数据失败:", error);
    proxy.$modal.msgError("获取提案数据失败");
  });
}


function handleScoreInput(fieldName, value) {
  // 如果输入为空或空字符串，设置为null
  if (value === '' || value === null || value === undefined) {
    scoreForm.value[fieldName] = null;
  } else {
    // 尝试转换为数字
    const numValue = Number(value);
    // 如果是有效数字，使用数字值，否则保持原值
    if (!isNaN(numValue)) {
      scoreForm.value[fieldName] = numValue;
    } else {
      scoreForm.value[fieldName] = value;
    }
  }
}

/** 处理可行性评估结果变更 */
function handleFeasibilityResultChange(value) {
  // 如果选择了"不采纳"，则设置奖金为5，清空评分项
  if (value === '不采纳') {
    scoreForm.value.bonus = 5;
    scoreForm.value.status = '驳回';
    clearScoreFields();
    scoreForm.value.supervisorTotalScore = 0;
    scoreForm.value.managerTotalScore = 0;
    scoreForm.value.committeeTotalScore = null;
  }
}

/** 清空评分字段 */
function clearScoreFields() {
  // 清空主管评分项
  scoreForm.value.supervisorCompleteness = null;
  scoreForm.value.supervisorApplicability = null;
  scoreForm.value.supervisorInnovation = null;
  scoreForm.value.supervisorSafetyEnvironment = null;
  scoreForm.value.supervisorQuality = null;
  scoreForm.value.supervisorEfficiency = null;
  scoreForm.value.supervisorCost = null;
  scoreForm.value.supervisorPromotion = null;
  scoreForm.value.supervisorEffort = null;
  scoreForm.value.supervisorTotalScore = null;

  // 清空经理评分项
  scoreForm.value.managerCompleteness = null;
  scoreForm.value.managerApplicability = null;
  scoreForm.value.managerInnovation = null;
  scoreForm.value.managerSafetyEnvironment = null;
  scoreForm.value.managerQuality = null;
  scoreForm.value.managerEfficiency = null;
  scoreForm.value.managerCost = null;
  scoreForm.value.managerPromotion = null;
  scoreForm.value.managerEffort = null;
  scoreForm.value.managerTotalScore = null;

  // 清空委员会评分项
  scoreForm.value.committeeCompleteness = null;
  scoreForm.value.committeeApplicability = null;
  scoreForm.value.committeeInnovation = null;
  scoreForm.value.committeeSafetyEnvironment = null;
  scoreForm.value.committeeQuality = null;
  scoreForm.value.committeeEfficiency = null;
  scoreForm.value.committeeCost = null;
  scoreForm.value.committeePromotion = null;
  scoreForm.value.committeeEffort = null;
  scoreForm.value.committeeTotalScore = null;
}

/** 计算主管总分 */
function supervisorTotalScore() {
  // 只有当至少有一个主管评分项不为null时才计算总分
  if (scoreForm.value.supervisorCompleteness !== null || 
      scoreForm.value.supervisorApplicability !== null || 
      scoreForm.value.supervisorInnovation !== null || 
      scoreForm.value.supervisorSafetyEnvironment !== null || 
      scoreForm.value.supervisorQuality !== null || 
      scoreForm.value.supervisorEfficiency !== null || 
      scoreForm.value.supervisorCost !== null || 
      scoreForm.value.supervisorPromotion !== null || 
      scoreForm.value.supervisorEffort !== null) {
    
    const supervisorTotal = 
      Number(scoreForm.value.supervisorCompleteness || 0) +
      Number(scoreForm.value.supervisorApplicability || 0) +
      Number(scoreForm.value.supervisorInnovation || 0) +
      Number(scoreForm.value.supervisorSafetyEnvironment || 0) +
      Number(scoreForm.value.supervisorQuality || 0) +
      Number(scoreForm.value.supervisorEfficiency || 0) +
      Number(scoreForm.value.supervisorCost || 0) +
      Number(scoreForm.value.supervisorPromotion || 0) +
      Number(scoreForm.value.supervisorEffort || 0);
      
    scoreForm.value.supervisorTotalScore = supervisorTotal > 0 ? supervisorTotal : null;
  } else {
    // 如果所有评分项都为null，则总分也设为null
    scoreForm.value.supervisorTotalScore = null;
  }
}

/** 计算经理总分 */
function managerTotalScore() {
  // 只有当至少有一个经理评分项不为null时才计算总分
  if (scoreForm.value.managerCompleteness !== null || 
      scoreForm.value.managerApplicability !== null || 
      scoreForm.value.managerInnovation !== null || 
      scoreForm.value.managerSafetyEnvironment !== null || 
      scoreForm.value.managerQuality !== null || 
      scoreForm.value.managerEfficiency !== null || 
      scoreForm.value.managerCost !== null || 
      scoreForm.value.managerPromotion !== null || 
      scoreForm.value.managerEffort !== null) {
    
    const managerTotal = 
      Number(scoreForm.value.managerCompleteness || 0) +
      Number(scoreForm.value.managerApplicability || 0) +
      Number(scoreForm.value.managerInnovation || 0) +
      Number(scoreForm.value.managerSafetyEnvironment || 0) +
      Number(scoreForm.value.managerQuality || 0) +
      Number(scoreForm.value.managerEfficiency || 0) +
      Number(scoreForm.value.managerCost || 0) +
      Number(scoreForm.value.managerPromotion || 0) +
      Number(scoreForm.value.managerEffort || 0);
      
    scoreForm.value.managerTotalScore = managerTotal > 0 ? managerTotal : null;
  } else {
    // 如果所有评分项都为null，则总分也设为null
    scoreForm.value.managerTotalScore = null;
  }
}

/** 计算委员会总分 */
function committeeTotalScore() {
  // 检查是否有任何评分项不为null
  const hasScores = [
    scoreForm.value.committeeCompleteness,
    scoreForm.value.committeeApplicability,
    scoreForm.value.committeeInnovation,
    scoreForm.value.committeeSafetyEnvironment,
    scoreForm.value.committeeQuality,
    scoreForm.value.committeeEfficiency,
    scoreForm.value.committeeCost,
    scoreForm.value.committeePromotion,
    scoreForm.value.committeeEffort
  ].some(score => score !== null && score !== undefined && score !== '');
  
  if (hasScores) {
    const committeeTotal = 
      Number(scoreForm.value.committeeCompleteness || 0) +
      Number(scoreForm.value.committeeApplicability || 0) +
      Number(scoreForm.value.committeeInnovation || 0) +
      Number(scoreForm.value.committeeSafetyEnvironment || 0) +
      Number(scoreForm.value.committeeQuality || 0) +
      Number(scoreForm.value.committeeEfficiency || 0) +
      Number(scoreForm.value.committeeCost || 0) +
      Number(scoreForm.value.committeePromotion || 0) +
      Number(scoreForm.value.committeeEffort || 0);
      
    // 如果总分大于0，则设置总分，否则设置为null
    scoreForm.value.committeeTotalScore = committeeTotal > 0 ? committeeTotal : null;
  } else {
    // 如果所有评分项都为null，则总分也设为null
    scoreForm.value.committeeTotalScore = null;
  }
}


/** 设置提案状态 */
function setProposalStatus() {
  // 如果选择了"不采纳"，状态为"驳回"
  if (scoreForm.value.feasibilityResult === '不采纳') {
    scoreForm.value.status = '驳回';
    return;
  }

  // 根据评分自动设置状态
  const { managerTotalScore, committeeTotalScore } = scoreForm.value;
  
  // 如果委员会已评分，则状态为"已采纳"
  if (committeeTotalScore !== null) {
    scoreForm.value.status = '已采纳';
    return;
  }
  
  // 如果经理已评分，根据分数判断状态
  if (managerTotalScore !== null) {
    if (managerTotalScore >= 30) {
      // 分数大于等于30分，需要等待委员会评分
      scoreForm.value.status = '待委员会评分';
    } else {
      // 分数小于30分，自动变为已采纳
      scoreForm.value.status = '已采纳';
    }
    return;
  }
  
  // 默认状态
  scoreForm.value.status = '评分中';
}

/** 提交评分 */
function submitScoreForm(submitType) {
  proxy.$refs["scoreRef"].validate(valid => {
    if (valid) {
      
      supervisorTotalScore();
      managerTotalScore();
      committeeTotalScore();
      scoreForm.value.bonus = calculateBonus(scoreForm.value);
      setProposalStatus(); // 设置提案状态

      // 构建提交数据
      const submitData = {
        id: scoreForm.value.id,
        // 基本信息
        status: scoreForm.value.status,
        month: scoreForm.value.month,
        departmentName: scoreForm.value.departmentName,
        proposerName: scoreForm.value.proposerName,
        proposalTime: scoreForm.value.proposalTime,
        proposalTypeName: scoreForm.value.proposalTypeName,
        title: scoreForm.value.title,
        categoryName: scoreForm.value.categoryName,
        isCompanyPromoted: scoreForm.value.isCompanyPromoted,
        isFinancePromoted: scoreForm.value.isFinancePromoted,
        isQualityPromoted: scoreForm.value.isQualityPromoted,
        image: scoreForm.value.image,
        
        // 可行性评估
        feasibilityDepartment: scoreForm.value.feasibilityDepartment,
        feasibilityResult: scoreForm.value.feasibilityResult,
        feasibilityTime: scoreForm.value.feasibilityTime,
        feasibilityOpinion: scoreForm.value.feasibilityOpinion,
        bonus: Number(scoreForm.value.bonus),
      };

      // 如果选择了"不采纳"，清空所有评分项
      if (scoreForm.value.feasibilityResult === '不采纳') {
        // 明确设置总分为0，确保数据库中的值被更新
        submitData.supervisorTotalScore = 0;
        submitData.managerTotalScore = 0;
        submitData.committeeTotalScore = 0;
      } else {
        // 直接提交
        // 主管评分项
        submitData.supervisorCompleteness = scoreForm.value.supervisorCompleteness !== null ? 
          Number(scoreForm.value.supervisorCompleteness) : null;
        submitData.supervisorApplicability = scoreForm.value.supervisorApplicability !== null ? 
          Number(scoreForm.value.supervisorApplicability) : null;
        submitData.supervisorInnovation = scoreForm.value.supervisorInnovation !== null ? 
          Number(scoreForm.value.supervisorInnovation) : null;
        submitData.supervisorSafetyEnvironment = scoreForm.value.supervisorSafetyEnvironment !== null ? 
          Number(scoreForm.value.supervisorSafetyEnvironment) : null;
        submitData.supervisorQuality = scoreForm.value.supervisorQuality !== null ? 
          Number(scoreForm.value.supervisorQuality) : null;
        submitData.supervisorEfficiency = scoreForm.value.supervisorEfficiency !== null ? 
          Number(scoreForm.value.supervisorEfficiency) : null;
        submitData.supervisorCost = scoreForm.value.supervisorCost !== null ? 
          Number(scoreForm.value.supervisorCost) : null;
        submitData.supervisorPromotion = scoreForm.value.supervisorPromotion !== null ? 
          Number(scoreForm.value.supervisorPromotion) : null;
        submitData.supervisorEffort = scoreForm.value.supervisorEffort !== null ? 
          Number(scoreForm.value.supervisorEffort) : null;

        // 经理评分项
        submitData.managerCompleteness = scoreForm.value.managerCompleteness !== null ? 
          Number(scoreForm.value.managerCompleteness) : null;
        submitData.managerApplicability = scoreForm.value.managerApplicability !== null ? 
          Number(scoreForm.value.managerApplicability) : null;
        submitData.managerInnovation = scoreForm.value.managerInnovation !== null ? 
          Number(scoreForm.value.managerInnovation) : null;
        submitData.managerSafetyEnvironment = scoreForm.value.managerSafetyEnvironment !== null ? 
          Number(scoreForm.value.managerSafetyEnvironment) : null;
        submitData.managerQuality = scoreForm.value.managerQuality !== null ? 
          Number(scoreForm.value.managerQuality) : null;
        submitData.managerEfficiency = scoreForm.value.managerEfficiency !== null ? 
          Number(scoreForm.value.managerEfficiency) : null;
        submitData.managerCost = scoreForm.value.managerCost !== null ? 
          Number(scoreForm.value.managerCost) : null;
        submitData.managerPromotion = scoreForm.value.managerPromotion !== null ? 
          Number(scoreForm.value.managerPromotion) : null;
        submitData.managerEffort = scoreForm.value.managerEffort !== null ? 
          Number(scoreForm.value.managerEffort) : null;

        // 委员会评分项
        submitData.committeeCompleteness = scoreForm.value.committeeCompleteness !== null ? 
          Number(scoreForm.value.committeeCompleteness) : null;
        submitData.committeeApplicability = scoreForm.value.committeeApplicability !== null ? 
          Number(scoreForm.value.committeeApplicability) : null;
        submitData.committeeInnovation = scoreForm.value.committeeInnovation !== null ? 
          Number(scoreForm.value.committeeInnovation) : null;
        submitData.committeeSafetyEnvironment = scoreForm.value.committeeSafetyEnvironment !== null ? 
          Number(scoreForm.value.committeeSafetyEnvironment) : null;
        submitData.committeeQuality = scoreForm.value.committeeQuality !== null ? 
          Number(scoreForm.value.committeeQuality) : null;
        submitData.committeeEfficiency = scoreForm.value.committeeEfficiency !== null ? 
          Number(scoreForm.value.committeeEfficiency) : null;
        submitData.committeeCost = scoreForm.value.committeeCost !== null ? 
          Number(scoreForm.value.committeeCost) : null;
        submitData.committeePromotion = scoreForm.value.committeePromotion !== null ? 
          Number(scoreForm.value.committeePromotion) : null;
        submitData.committeeEffort = scoreForm.value.committeeEffort !== null ? 
          Number(scoreForm.value.committeeEffort) : null;

        // 总分
        submitData.supervisorTotalScore = scoreForm.value.supervisorTotalScore !== null ? 
          Number(scoreForm.value.supervisorTotalScore) : null;
        submitData.managerTotalScore = scoreForm.value.managerTotalScore !== null ? 
          Number(scoreForm.value.managerTotalScore) : null;
        submitData.committeeTotalScore = scoreForm.value.committeeTotalScore !== null ? 
          Number(scoreForm.value.committeeTotalScore) : null;
      }

      //console.log("提交类型:", submitType, "提交数据:", submitData);
      submitScore(submitData).then(response => {
        proxy.$modal.msgSuccess("评分提交成功");
        scoreOpen.value = false;
        getList();
      }).catch((error) => {
        //console.error("评分提交失败:", error);
        proxy.$modal.msgError("评分提交失败");
      });
    }
  });
}


/** 页面加载时获取数据 */
getList();
</script>

<style scoped>
.proposal-form {
  padding: 20px;
}

.mb-3 {
  margin-bottom: 15px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.section-title {
  font-weight: bold;
  margin: 15px 0 10px 0;
  color: #666;
}

.form-footer {
  text-align: center;
  padding: 20px 0;
}

:deep(.el-card__header) {
  padding: 10px 20px;
  background-color: #f5f7fa;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}

.proposal-content {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #333;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #eee;
  min-height: 20px;
}

.score-legend {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.legend-item {
  margin-right: 20px;
  display: inline-flex;
  align-items: center;
}

.legend-color {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 5px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.content-preview {
  max-height: 100px;
  overflow-y: auto;
  white-space: pre-wrap;
  line-height: 1.5;
  padding: 5px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  transition: all 0.3s ease;
}

.content-preview:hover {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-color: #dcdfe6;
}

.current-scores {
  padding: 10px 0;
}

.current-scores p {
  margin: 8px 0;
  font-size: 14px;
}

.current-scores strong {
  color: #409EFF;
}

/* 新增样式：确保左右两侧宽度一致 */
.score-info-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.score-info-card .el-descriptions {
  flex: 1;
}

.score-info-card .el-divider {
  margin: 10px 0;
}

.score-info-card .current-scores {
  padding: 10px 0;
  margin-top: auto;
}
</style>